﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using SportsStore.Logging;
using SportsStoreLogService;

namespace SportsStore.Web
{
  // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
  // visit http://go.microsoft.com/?LinkId=9394801
  public class MvcApplication : System.Web.HttpApplication
  {
    protected void Application_Start()
    {
      var builder = new ContainerBuilder();
      builder.RegisterControllers(typeof(MvcApplication).Assembly);
      RegisterTypes(builder);
      builder.RegisterFilterProvider();
      var container = builder.Build();
      DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

      AreaRegistration.RegisterAllAreas();

      WebApiConfig.Register(GlobalConfiguration.Configuration);
      FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
      RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

    private void RegisterTypes(ContainerBuilder builder)
    {
      string ctor = ConfigurationManager.ConnectionStrings["SportsStore"].ConnectionString;
      var repositoryAssemblies = Assembly.Load("SportsStore.Repository");
      builder.RegisterAssemblyTypes(repositoryAssemblies).AsImplementedInterfaces().WithParameter(new NamedParameter("connectionString", ctor)).InstancePerHttpRequest();
      var serviceAssemblies = Assembly.Load("SportsStore.Services");
      builder.RegisterAssemblyTypes(serviceAssemblies).AsImplementedInterfaces();

      builder.RegisterType<NLogService>().As<ILogger>();
    }
  }
}